import type { FC} from 'react';
import React, { useEffect } from 'react';
import type { ConnectState } from '@/models/connect';
import type { ConnectProps} from 'umi';
import { connect,useHistory } from 'umi';
import './BasicLayout.less';
import MenuBar from '@/components/MenuBar';
import { Modal} from 'antd-mobile';
import { getMenuRoute, formatterMenu } from '@/utils/utils';
import { FROMKEY } from '@/common/const';
import { storage, LOCALSTATE } from '@/utils';
import { commonMenu } from '@/common';
import { CurrentUser } from '@/models/user';
// import {  Prompt } from 'react-router-dom'
import NavigationBar from '@/components/NavigationBar';
import wxJS from '@/utils/wx.sdk';
import { navigationRef } from '@/utils/nav';

interface BasicLayoutProps extends Required<ConnectProps> {
  prefixCls?: string;
  route: any;
  loading: boolean;
  currentUser: any;
}

const BasicLayout: FC<BasicLayoutProps> = (props) => {
  const { children, prefixCls, route, location, currentUser } = props;
  const { pathname, query } = location as any;
  const history = useHistory();
  // 是否小程序
  const isMiniPrograms = wxJS.isMiniPrograms();
  /**
   * 存储平台类型FROM字段
   */
  if (query.from) {
    storage.set(FROMKEY, query.from);
  }
  useEffect(()=>{
    const { dispatch } = props;
    storage.set(FROMKEY, query.from); 
    const local: any = storage.get(LOCALSTATE,true)||{}
    if(!currentUser?.userUuid){
      dispatch({
        type: 'user/fetchCurrent',
      });
    }
  },[])
  const { routes } = route;
  const menuRoute = getMenuRoute(routes);
  const allRoutes = formatterMenu(routes);
  const currentRoute = allRoutes.find((item) => item.path === pathname);
  if (currentRoute && currentRoute.title) {
    document.title = currentRoute.title;
  }
  // const currentRoute = (allRoutes && allRoutes.find((r) => r.path === pathname)) || {};
  if (menuRoute.indexOf(pathname) >= 0) {
    return (
      <div className={prefixCls}>
        <MenuBar menus={commonMenu} routes={routes} pathname={pathname}>
          {children}
        </MenuBar>
      </div>
    );
  }
  return (
    <div className={prefixCls}>
      {/* <Prompt
          when
          message={(location ,action) => {
            // 浏览器回退
            if(action==='POP'){
              Modal.alert('如需返回上一页请点击上一步！', '', [
                {
                  text: '确定',
                  onPress: () => {
                  }
                }
              ])
              return false
            }
            
          }}
      /> */}
      {(currentRoute&&!currentRoute.path.includes('/home'))&&<NavigationBar ref={navigationRef} title={currentRoute?.title || ''} />}
      {children}
    </div>
  );
};

BasicLayout.defaultProps = {
  prefixCls: 'basic-layout',
};


export default connect(({ user, loading }: ConnectState) => ({
  loading: loading.effects['user/fetchCurrent'],
  currentUser: user.currentUser,
}))(BasicLayout);
